package com.upbos.upm.org;

import com.upbos.core.ret.RetCode;
import com.upbos.core.ret.RetData;
import com.upbos.data.core.Pagination;
import com.upbos.sso.UserContext;
import com.upbos.upm.common.Constants;
import com.upbos.upm.dept.DeptService;
import com.upbos.upm.entity.Dept;
import com.upbos.upm.entity.Org;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <b>Application name：</b> OrgService.java <br>
 * <b>Application describing：组织机构管理Service </b> <br>
 * <b>Copyright：</b> Copyright &copy; 2019 upbos.com 版权所有。<br>
 * <b>Company：</b> upbos.com <br>
 * <b>@Date：</b> 2019年11月08日 13:59 <br>
 * <b>@author：</b> <a href="mailto:Jason@miyzh.com"> Jason </a> <br>
 * <b>@version：</b>V5.0.0 <br>
 */
@Service
public class OrgService {
    @Resource
    private OrgDao orgDao;

    @Resource
    private DeptService deptService;


    public RetData<Org> listOrg(String orgName, UserContext context) {
        RetData<Org> retData = RetData.ret(RetCode.SUCCESS);
        boolean hasAdmin = context.hasPrivilege(Constants.PRIVILEGE_ADMIN_KEY);
        retData.putData("visible", hasAdmin);
        retData.putData("dataSource", orgDao.listOrg(orgName, hasAdmin ? null : context.getSsoUser().getOrgId()));
        return retData;
    }

    /**
     * 根据组织机构名称模糊查询
     *
     * @param name 组织机构名称
     * @return 组织机构列表
     */
    public Pagination<Org> listOrgByName(Integer pageNo, Integer pageSize, String type, String name) {
        return orgDao.listOrgByName(pageNo, pageSize, type, name);
    }

    @Transactional(rollbackFor = Exception.class)
    public Org saveOrg(Org org) {
        if (org.getId() == null) {
            // 插入组织机构
            insertOrg(org);
            // 插入缺省部门
            Dept dept = new Dept();
            dept.setOrgId(org.getId());
            dept.setName("缺省部门");
            dept.setRemark("缺省部门描述");
            dept.setStatus(true);
            deptService.insertDept(dept);
        } else {
            // 更新组织机构
            orgDao.updateOrg(org);
        }
        return org;
    }

    /**
     * 插入组织机构
     *
     * @param org
     */
    private void insertOrg(Org org) {
        orgDao.insertOrg(org);
    }

    @Transactional(rollbackFor = Exception.class)
    public RetData deleteOrg(Org org) {
        RetData retData = new RetData(RetCode.SUCCESS);
        if (orgDao.getOrgDeptCount(org.getId()) > 0 ||
                orgDao.getOrgRoleCount(org.getId()) > 0 ||
                orgDao.getOrgUserCount(org.getId()) > 0) {
            retData.setCode(RetCode.FAIL, "该机构下还有部门、角色或者用户，请先行删除！");
            return retData;
        }
        orgDao.deleteOrg(org);
        return retData;
    }


}
